/*
 * Copyright 2020-2025 the original author or authors.
 * You cannot use this file unless authorized by the author.
 */
package org.ipig.query;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.Getter;
import lombok.ToString;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;

/**
 * QueryResult
 *
 * @author <a href="mailto:comchnts@163.com">chinats</a>
 * @version $$Id: QueryResult.java 3 2020-01-21 09:36:33Z ts <comchnts@163.com> $$
 * @since 1.0
 */
@ToString
public class QueryResult implements Serializable {
    private QuerySo so;
    //状态 0 成功 ，非0失败
    @Getter
    private String status;
    //消息
    @Getter
    private String message;
    //业务对象
    @Getter
    private JSONObject payload;


    public QueryResult(QuerySo so, String resultMsg) {
        this.so = so;
        if (StringUtils.isNoneBlank(resultMsg)) {
            JSONObject resultObject = JSON.parseObject(resultMsg);
            if (resultObject != null) {
                payload = resultObject.getJSONObject("payload");
                status = resultObject.getString("status");
                message = resultObject.getString("message");
            }
        }
    }

    /**
     * 根据指标查询
     *
     * @param var QueryVar
     */
    public String getResult(QueryVar var) {
        String result = StringUtils.EMPTY;
        if (payload != null && !payload.isEmpty() && StringUtils.equals(status, "0")) {
            JSONObject bizJsonObject = payload.getJSONObject(so.getBiz());
            if (bizJsonObject != null && !bizJsonObject.isEmpty()) {
                JSONObject dimJsonObject = bizJsonObject.getJSONObject(so.getDim());
                if (dimJsonObject != null && !dimJsonObject.isEmpty()) {
                    JSONObject metricsResult = dimJsonObject.getJSONObject(so.getKey());
                    if (metricsResult != null && !metricsResult.isEmpty()) {
                        result = metricsResult.getString(var.getName());
                    }
                }
            }
        }
        return result;
    }
}
